<template>
  <div>
    <el-dialog
      title="导出数据"
      :visible.sync="dialogVisible"
      v-dialogDrag
      @close="handleCancelDialog"
      width="700px"
      class="export-excel-dialog"
      :close-on-click-modal="false">
      <div class="dialog-content">
        <el-form ref="exportForm" :model="exportData" label-width="100px" class="export-form">
          <!-- 选择测点 -->
          <el-form-item label="选择测点" class="form-section">
            <div class="point-selector">
              <el-select 
                v-model="menuSelModel" 
                placeholder="请选择测点类型" 
                size="small"
                @change="handleChangePoint"
                class="type-selector">
                <el-option
                  v-for="item in menuSeloptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              
              <div class="selection-info">
                <el-alert
                  :title="selectionInfo"
                  :type="exportArr.length > 30 ? 'error' : 'warning'"
                  :closable="false"
                  show-icon
                  class="selection-alert">
                </el-alert>
              </div>
              
              <div class="tree-container">
                <el-tree
                  ref="exportTree"
                  class="export-tree"
                  :data="menuList"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  show-checkbox
                  node-key="treeid"
                  @check-change="handleChangeTree"
                  :default-expand-all="false">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
              </div>
            </div>
          </el-form-item>
          
          <!-- 数据时间 -->
          <el-form-item label="数据时间" class="form-section">
            <div class="date-range">
              <el-date-picker
                v-model="exportData.startTime"
                type="date"
                placeholder="开始时间"
                value-format="yyyy/MM/dd"
                size="small"
                class="date-picker">
              </el-date-picker>
              <span class="date-separator">至</span>
              <el-date-picker
                v-model="exportData.endTime"
                type="date"
                value-format="yyyy/MM/dd"
                placeholder="结束时间"
                size="small"
                class="date-picker">
              </el-date-picker>
            </div>
            <el-alert
              title="如果不选择数据时间，则默认导出所有时间段的数据"
              type="info"
              :closable="false"
              show-icon
              class="info-alert">
            </el-alert>
          </el-form-item>
          
          <!-- 数据顺序 -->
          <el-form-item label="数据顺序" class="form-section">
            <el-radio-group v-model="exportData.timeSequence" size="small">
              <el-radio-button label="正序">正序</el-radio-button>
              <el-radio-button label="倒序">倒序</el-radio-button>
            </el-radio-group>
          </el-form-item>
          
          <!-- 数据过滤 -->
          <el-form-item label="数据过滤" class="form-section">
            <div class="filter-container">
              <div class="filter-group">
                <div class="filter-label">测值类型</div>
                <el-checkbox-group v-model="valueTypeCheckboxes" class="checkbox-group">
                  <el-checkbox label="h">初始值</el-checkbox>
                  <el-checkbox label="i">中间值</el-checkbox>
                  <el-checkbox label="j">成果值</el-checkbox>
                </el-checkbox-group>
              </div>
              
              <div class="filter-group">
                <div class="filter-label">测值状态</div>
                <el-checkbox-group v-model="valueStatusCheckboxes" class="checkbox-group">
                  <el-checkbox label="a">正常</el-checkbox>
                  <el-checkbox label="b">异常</el-checkbox>
                  <el-checkbox label="c">错误</el-checkbox>
                  <el-checkbox label="d">未判定</el-checkbox>
                </el-checkbox-group>
              </div>
              
              <div class="filter-group">
                <div class="filter-label">审核状态</div>
                <el-checkbox-group v-model="reviewStatusCheckboxes" class="checkbox-group">
                  <el-checkbox label="e">未审核</el-checkbox>
                  <el-checkbox label="f">通过</el-checkbox>
                  <el-checkbox label="g">未通过</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
        </el-form>
        
        <!-- 操作按钮 -->
        <div class="dialog-footer">
          <el-button 
            @click="handleCancelDialog" 
            size="small" 
            icon="el-icon-circle-close"
            class="cancel-btn">
            取消
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleConfirmDialog" 
            :loading="exportLoading" 
            :disabled="exportArr.length > 30"
            icon="el-icon-download"
            class="confirm-btn">
            {{ exportLoading ? '导出中...' : '导出' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetTreeStyle, GetTreeInstr, GetOuputmonitoringData } from "@/api/https";

export default {
  name: "ExportExcel",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    stationId: {
      type: [String, Number],
      default: ''
    },
  },
  data() {
    return {
      dialogVisible: false,
      menuSelModel: '',
      menuSeloptions: [],
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'lable'
      },
      exportArr: [],
      exportLoading: false,
      exportData: {
        stationID: this.stationId,
        treeIDs: [],
        startTime: '',
        endTime: '',
        pageIndex: 1,
        pageSize: 50,
        timeSequence: '倒序',
        a: true,
        b: true,
        c: true,
        d: true,
        e: true,
        f: true,
        g: true,
        h: true,
        i: true,
        j: true,
        valueType: 6,
      },
      valueTypeCheckboxes: ['h', 'i', 'j'],
      valueStatusCheckboxes: ['a', 'b', 'c', 'd'],
      reviewStatusCheckboxes: ['e', 'f', 'g']
    };
  },
  computed: {
    selectionInfo() {
      if (this.exportArr.length > 30) {
        return `已选择${this.exportArr.length}个测点，最多只能选择30个测点。`;
      } else {
        return `已选择${this.exportArr.length}个测点`;
      }
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal;
      if (newVal) {
        this.getMenuSelectOption();
      }
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal);
    },
    valueTypeCheckboxes: {
      handler(newVal) {
        this.exportData.h = newVal.includes('h');
        this.exportData.i = newVal.includes('i');
        this.exportData.j = newVal.includes('j');
        this.calculateValueType();
      },
      deep: true
    },
    valueStatusCheckboxes: {
      handler(newVal) {
        this.exportData.a = newVal.includes('a');
        this.exportData.b = newVal.includes('b');
        this.exportData.c = newVal.includes('c');
        this.exportData.d = newVal.includes('d');
      },
      deep: true
    },
    reviewStatusCheckboxes: {
      handler(newVal) {
        this.exportData.e = newVal.includes('e');
        this.exportData.f = newVal.includes('f');
        this.exportData.g = newVal.includes('g');
      },
      deep: true
    }
  },
  methods: {
    getMenuSelectOption() {
      GetTreeStyle(this.stationId).then(res => {
        if (res.isSuccess && res.data && res.data.length > 0) {
          this.menuSeloptions = res.data || [];
          if (this.menuSelModel === '') {
            this.menuSelModel = res.data[0];
          }
          this.getTreeData();
        } else {
          this.menuSeloptions = [];
          this.menuSelModel = '';
        }
      }).catch(error => {
        console.error('获取测点类型失败:', error);
        this.$message.error('获取测点类型失败');
      });
    },
    getTreeData() {
      GetTreeInstr(this.stationId, this.menuSelModel).then(res => {
        if (res.isSuccess) {
          this.menuList = res.data || [];
        } else {
          this.menuList = [];
        }
      }).catch(error => {
        console.error('获取测点数据失败:', error);
        this.$message.error('获取测点数据失败');
      });
    },
    handleCancelDialog() {
      this.resetForm();
      this.dialogVisible = false;
    },
    handleChangePoint(val) {
      this.menuSelModel = val;
      this.getTreeData();
      // 清空已选择的测点
      this.$refs.exportTree.setCheckedKeys([]);
      this.exportArr = [];
    },
    handleChangeTree() {
      let checkedNodes = this.$refs.exportTree.getCheckedNodes();
      const list = [];
      checkedNodes.forEach(item => {
        if (item.node.treeid && item.node.treeid.toString().length === 7) {
          list.push(item.node.treeid);
        }
      });
      this.exportArr = list;
    },
    calculateValueType() {
      const { h, i, j } = this.exportData;
      
      if (!h && !i && !j) return -1;
      if (h && !i && !j) return 0;
      if (!h && i && !j) return 1;
      if (!h && !i && j) return 2;
      if (h && i && !j) return 3;
      if (h && !i && j) return 4;
      if (!h && i && j) return 5;
      if (h && i && j) return 6;
      
      return 6; // 默认值
    },
    async handleConfirmDialog() {
      if (this.exportArr.length > 30) {
        this.$message.error('最多只能选择30个测点！');
        return;
      }
      
      if (this.exportArr.length === 0) {
        this.$message.warning('请至少选择一个测点');
        return;
      }
      
      // 更新valueType
      this.exportData.valueType = this.calculateValueType();
      
      // 设置treeIDs
      this.exportData.treeIDs = this.exportArr;
      
      this.exportLoading = true;
      
      try {
        const res = await GetOuputmonitoringData(this.exportData);
        
        if (res.data) {
          const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          
          const now = new Date();
          const timeName = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}-${now.getHours()}${now.getMinutes()}${now.getSeconds()}`;
          link.download = `${timeName}监测数据导出.xls`;
          
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
          }, 100);
          
          this.$message.success('导出成功！');
          this.handleCancelDialog();
        } else {
          this.$message.error('导出失败，返回数据为空');
        }
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请联系管理员！');
      } finally {
        this.exportLoading = false;
      }
    },
    resetForm() {
      this.exportData = {
        stationID: this.stationId,
        treeIDs: [],
        startTime: '',
        endTime: '',
        pageIndex: 1,
        pageSize: 50,
        timeSequence: '倒序',
        a: true,
        b: true,
        c: true,
        d: true,
        e: true,
        f: true,
        g: true,
        h: true,
        i: true,
        j: true,
        valueType: 6,
      };
      
      this.valueTypeCheckboxes = ['h', 'i', 'j'];
      this.valueStatusCheckboxes = ['a', 'b', 'c', 'd'];
      this.reviewStatusCheckboxes = ['e', 'f', 'g'];
      
      if (this.$refs.exportTree) {
        this.$refs.exportTree.setCheckedKeys([]);
      }
      
      this.exportArr = [];
      this.exportLoading = false;
    }
  }
};
</script>

<style scoped>
.export-excel-dialog {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
}

.dialog-content {
  padding: 0 10px;
}

.export-form {
  margin-top: -10px;
}

.form-section {
  margin-bottom: 20px;
}

.point-selector {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.type-selector {
  width: 200px;
}

.selection-alert {
  padding: 0px 16px;
}

.tree-container {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
  background-color: #f9f9f9;
}

.export-tree {
  height: 140px;
  overflow: auto;
  background-color: white;
  padding: 5px;
  border-radius: 3px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-picker {
  width: 150px;
}

.date-separator {
  color: #909399;
  font-size: 14px;
}

.info-alert {
  margin-top: 10px;
  padding: 0px 16px;
}

.filter-container {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-group {
  display: flex;
  align-items: flex-start;
}

.filter-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
  line-height: 32px;
}

.checkbox-group {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e6e6e6;
}

.cancel-btn {
  width: 80px;
}

.export-btn {
  width: 100px;
}

</style>